"""
服务器相关工具
"""
from typing import Dict, List, Optional
from django.db.models import Q
from django_mcp import mcp_app as mcp
from mcp.server.fastmcp import Context
from api.models import Server
from api.serializers import ServerSerializer, ServerDetailSerializer
from asgiref.sync import sync_to_async


@mcp.tool()
async def list_servers(ctx: Context, page: int = 1, page_size: int = 10, search: str = None) -> Dict:
    """
    获取服务器列表，支持分页和搜索
    
    参数:
    - page: 页码，默认为1
    - page_size: 每页数量，默认为10
    - search: 搜索关键词，可搜索服务器名称、IP地址等
    
    返回:
    - servers: 服务器列表
    - total: 服务器总数
    - page: 当前页码
    - page_size: 每页数量
    - total_pages: 总页数
    """
    try:
        # 构建查询
        queryset = await Server.objects.all()
        
        # 应用搜索过滤
        if search:
            queryset = queryset.filter(
                Q(name__icontains=search) |
                Q(description__icontains=search)
            )
        
        # 获取服务器总数
        total_servers = queryset.count()
        
        # 计算分页参数
        offset = (page - 1) * page_size
        
        # 获取分页后的服务器列表
        servers = queryset[offset:offset + page_size]
        
        # 计算总页数
        total_pages = (total_servers + page_size - 1) // page_size
        
        # 使用序列化器格式化数据
        serializer = sync_to_async(ServerSerializer(servers, many=True))
        
        return {
            "status": "success",
            "servers": serializer.data,
            "total": total_servers,
            "page": page,
            "page_size": page_size,
            "total_pages": total_pages
        }
        
    except Exception as e:
        error_msg = f"获取服务器列表时出错: {str(e)}"
        await ctx.error(error_msg)
        return {
            "status": "error",
            "message": error_msg
        }


@mcp.tool()
async def get_server_details(ctx: Context, server_id: str) -> Dict:
    """
    获取服务器详细信息
    
    参数:
    - server_id: 服务器ID
    
    返回:
    - server: 服务器详细信息
    """
    try:        
        # 获取服务器详情
        try:
            server = await Server.objects.get(id=server_id)
        except Server.DoesNotExist:
            return {
                "status": "error",
                "message": f"未找到ID为{server_id}的服务器"
            }
        
        # 使用详细序列化器格式化数据
        serializer = sync_to_async(ServerDetailSerializer(server))
        
        return {
            "status": "success",
            "server": serializer.data
        }
        
    except Exception as e:
        error_msg = f"获取服务器详情时出错: {str(e)}"
        await ctx.error(error_msg)
        return {
            "status": "error",
            "message": error_msg
        }

